package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexPatterns;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.KSQLJoinWindow;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpServletRequest session) {
        boolean matches = Pattern.matches(RegexPatterns.PHONE_REGEX, phone);
        if (matches == false) {
            return Result.fail("手机号格式错误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        //将验证码存到session中
//        session.getSession().setAttribute(phone, code);
        //将验证码存在Redis中
        stringRedisTemplate.opsForValue().set("login:code:"+phone,code,2, TimeUnit.MINUTES);
        log.info("验证码:" + code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpServletRequest session) {
        String phone = loginForm.getPhone();
        boolean matches = Pattern.matches(RegexPatterns.PHONE_REGEX, phone);
        if (matches == false) {
            return Result.fail("手机号格式错误");
        }
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        log.info("验证码:" + code);
        String code1 = loginForm.getCode();
        //验证码校验
        if (code == null || !code.equals(code1)) {
            return Result.fail("验证码错误！");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        User user = userMapper.selectOne(queryWrapper);
        String loginPhone = loginForm.getPhone();
        //手机号是否存在，不存在则创建
        if (user == null) {
            user.setPhone(loginPhone);
            user.setNickName("user_" + RandomUtil.randomString(10));
            userMapper.insert(user);
        }
        //随机生成Token,作为登录令牌
        String token = UUID.randomUUID().toString();
        System.out.println("token -------》" +token);
        //将User对象转换为Hash存储
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        //将对象转换成map
//        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((,fi)));

        Map<String, String> map = new HashMap<>();
        map.put("id",userDTO.getId().toString());
        map.put("nickName",userDTO.getNickName());
        map.put("icon",userDTO.getIcon());

        String tokenKey = RedisConstants.LOGIN_USER_KEY+token;
        //存储到Redis中
       stringRedisTemplate.opsForHash().putAll(tokenKey,map);
       //设置Token有效期
        stringRedisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);

        session.setAttribute("user", user);
        return Result.ok(token);
    }
}
